package org.mall.modules.cash.mq;

/***
 *@author yinxucun
 *@date 2020-01-05 16:54
 */

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayFundTransCommonQueryRequest;
import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
import com.github.binarywang.wxpay.bean.entpay.EntPayQueryResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.mall.common.constant.CashTransactionStatusEnum;
import org.mall.common.constant.PayChannelEnum;
import org.mall.common.util.json.JacksonUtils;
import org.mall.modules.cash.entity.CashInfoLog;
import org.mall.modules.cash.entity.CashTransaction;
import org.mall.modules.cash.mapper.CashInfoLogMapper;
import org.mall.modules.cash.mapper.CashTransactionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * 消息消费监听
 */
@Slf4j
@Component
public class ErrorCashTransactionListener implements MessageListenerConcurrently {
    @Autowired
    AlipayClient alipayClient;
    @Resource
    CashTransactionMapper cashTransactionMapper;
    @Resource
    CashInfoLogMapper cashInfoLogMapper;
    @Lazy
    @Qualifier("cashService")
    @Autowired
    WxPayService wxPayService;
    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext context) {
        if (CollectionUtils.isEmpty(list)){
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
        MessageExt messageExt = list.get(0);
        int reConsume = messageExt.getReconsumeTimes();
        CashTransaction cashTransaction= (CashTransaction) JacksonUtils.parseObject(new String(messageExt.getBody()), CashTransaction.class);

        // 消息已经重试了3次，如果不需要再次消费，则返回成功
        if(reConsume >=11){
            log.error("提现订单查询尝试了{}次,不再进行尝试关闭，提现订单:{}转手动关闭",reConsume-1,cashTransaction.getCashId());
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }
        CashTransaction db=cashTransactionMapper.selectByCashId(cashTransaction.getId());
        CashInfoLog cashInfoLog=cashInfoLogMapper.getDetailById(db.getCashId());
        if (cashInfoLog==null){
            log.error("发生异常，转账提现：{}的提现记录不存在",cashTransaction.getId());
        }
        if (PayChannelEnum.ALIPAY.getId().equals(cashInfoLog.getPayChannel())){
            AlipayFundTransCommonQueryRequest request = new AlipayFundTransCommonQueryRequest();
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("out_biz_no",db.getTradeNo());
            try {
                AlipayFundTransCommonQueryResponse response =alipayClient.execute(request);
                if (response.isSuccess()&&"SUCCESS".equals(response.getStatus())){
                    CashTransaction updateObj=new CashTransaction();
                    updateObj.setStatus(CashTransactionStatusEnum.SUCCESS.getValue()).setId(db.getId());
                    cashTransactionMapper.updateById(updateObj);
                    return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                }
            } catch (AlipayApiException e) {
                log.error("提现渠道:支付宝,查询失败,查询的提交记录id:{},失败代码:{},失败原因:{}",cashTransaction.getId(),e.getErrCode(),e.getErrMsg());
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }
        }

        if (PayChannelEnum.WEIXIN_APP.getId().equals(cashInfoLog.getPayChannel())){
            try {
                EntPayQueryResult result= wxPayService.getEntPayService().queryEntPay(String.valueOf(cashTransaction.getTradeNo()));
                if (WxPayConstants.ResultCode.SUCCESS.equals(result.getReturnCode())){
                    if (WxPayConstants.ResultCode.SUCCESS.equals(result.getResultCode())){
                        if ("PROCESSING".equals(result.getStatus())){
                            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
                        }
                        if ("SUCCESS".equals(result.getStatus())){
                            CashTransaction updateObj=new CashTransaction();
                            updateObj.setStatus(CashTransactionStatusEnum.SUCCESS.getValue()).setId(db.getId());
                            cashTransactionMapper.updateById(updateObj);
                            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                        }
                        if ("FAILED".equals(result.getStatus())){
                            CashTransaction updateObj=new CashTransaction();
                            updateObj.setStatus(CashTransactionStatusEnum.FAILURE.getValue()).setId(db.getId());
                            cashTransactionMapper.updateById(updateObj);
                            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
                        }
                    }
                }
            }catch (WxPayException e){
                log.error("提现渠道:微信支付,查询失败,查询的提交记录id:{},失败代码:{},失败原因:{}",cashTransaction.getId(),e.getErrCode(),e.getErrCodeDes());
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }

        }
        return ConsumeConcurrentlyStatus.RECONSUME_LATER;
    }
}

